package com.fau.cm.action.index;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.fau.cm.action.PublicAction;
import com.fau.cm.entity.MedicalAdmin;
import com.fau.cm.entity.MedicalCallCustomer;
import com.fau.cm.entity.MedicalOrders;
import com.fau.cm.util.FileNameEncoderUtil;
import com.fau.cm.util.SystemConfig;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @desc  客户管理Action
 * @author yangzj
 * @datetime 2014年10月14日,下午3:11:02
 */
@Controller
@Scope("prototype")
@ParentPackage("default")
@Namespace("/")
public class CustomerManageAction extends PublicAction implements ModelDriven<MedicalCallCustomer>{
	
	private static final long serialVersionUID = 6308437438609763549L;

	private MedicalCallCustomer customer = new MedicalCallCustomer();
	
	/**
	 * @desc 跳转到客户管理页面
	 * @return SUCCESS
	 * @author yangzj
	 * @datetime 2014年10月14日,下午3:14:41
	 */
	@Action(value = "customer_manage_init", results = {@Result(location = "customer_manage_init.jsp")})
	public String init(){
		return SUCCESS;
	}
	
	/**
	 * @desc 跳转到导入客户页面
	 * @return SUCCESS
	 * @author yangzj
	 * @datetime 2014年10月16日,下午5:57:29
	 */
	@Action(value = "import_customer_view", results = {@Result(location = "import_customer_view.jsp")})
	public String importView(){
		return SUCCESS;
	}
	
	/**
	 * @desc 分页查询客户信息
	 * @return null
	 * @author yangzj
	 * @datetime 2014年10月16日,下午5:15:24
	 */
	@Action(value = "customer_manage_view")
	public String view(){
		HttpServletResponse response = ServletActionContext.getResponse();
		this.map = ActionContext.getContext().getParameters();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		this.pageBean = this.baseAllService.getCustomerService().findCustomerByPage(admin, customer, map);
		this.map.clear();
		this.map.put("total", this.pageBean.getTotalRow());
		this.map.put("data", this.pageBean.getResult());
		formatJSON(response, this.map);
		return null;
	}
	
	/**
	 * @desc 导入客户信息
	 * @return null
	 * @author yangzj
	 * @datetime 2014年10月16日,下午6:10:40
	 */
	@Action(value="customer_import")
	public String importCustomer(){
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		map = new HashMap<String, Object>();
		File file = this.getImportFile(request);
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			String info = this.baseAllService.getCustomerService().importCustomer(admin, customer, file);
			if(info == null){
				map.put("success", true);
				map.put("message", "导入成功！");
				formatJSON(response, map);
			}else{
				map.put("success", false);
				map.put("message", info);
				formatJSON(response, map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * @desc 导出全部客户信息
	 * @return null
	 * @author yangzj
	 * @datetime 2014年10月17日,上午11:20:16
	 */
	@Action(value = "customer_details_export")
	public String export() {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		try {
			response.addHeader("Content-Disposition", "attachment;filename=" + FileNameEncoderUtil.encode(request,"客户信息.xls"));
			response.setContentType("application/vnd.ms-excel");
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			Workbook workbook = this.baseAllService.getCustomerService().exportCustomer(admin,this.customer);
			workbook.write(toClient);
			toClient.flush();
			toClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * @desc 导出当前页客户信息
	 * @return null
	 * @author yangzj
	 * @datetime 2014年10月17日,上午11:20:37
	 */
	@Action(value = "customer_details_current_export")
	public String currentExport(){
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		String ids = request.getParameter("ids");
		try {
			response.addHeader("Content-Disposition", "attachment;filename=" + FileNameEncoderUtil.encode(request,"客户信息.xls"));
			response.setContentType("application/vnd.ms-excel");
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			Workbook workbook = this.baseAllService.getCustomerService().currentExportCustomer(admin, ids);
			workbook.write(toClient);
			toClient.flush();
			toClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @desc 查询地址省
	 * @return
	 * @author kangyj
	 * @datetime 2014年11月8日,下午6:04:00
	 */
	@Action(value = "customer_manage_find_province")
	public String findProvinceList() {
		HttpServletResponse response = ServletActionContext.getResponse();
		list = this.baseAllService.getCustomerService().findProvinceList();
		formatJSON(response, list);
		return null;
	}
	
	/**
	 * @desc 根据省份id 查询地址城市集合
	 * @return
	 * @author kangyj
	 * @datetime 2014年11月8日,下午6:05:56
	 */
	@Action(value = "customer_manage_find_city")
	public String findCityList() {
		HttpServletResponse response = ServletActionContext.getResponse();
		list = this.baseAllService.getCustomerService().findCityListByPid(customer.getProvinceId());
		formatJSON(response, list);
		return null;
	}
	
	/**
	 * @desc 根据城市id 查询地区集合
	 * @return
	 * @author kangyj
	 * @datetime 2014年11月8日,下午6:08:10
	 */
	@Action(value = "customer_manage_find_district")
	public String findDistrictList() {
		HttpServletResponse response = ServletActionContext.getResponse();
		list = this.baseAllService.getCustomerService().findDistrictListByCid(customer.getCityId());
		formatJSON(response, list);
		return null;
	}
	
	/**
	 * @desc 转到选择推荐人页面
	 * @return
	 * @author kangyj
	 * @datetime 2014年11月9日,上午11:06:26
	 */
	@Action(value = "customer_manage_choose_rec", results = {@Result(location = "customer_manage_choose_rec.jsp")})
	public String chooseRec() {
		return SUCCESS;
	}
	
	/**
	 * @desc 查询推荐客户列表
	 * @return
	 * @author kangyj
	 * @datetime 2014年11月9日,上午11:09:33
	 */
	@Action(value = "customer_manage_find_rec")
	public String findrecCustomerList() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = ServletActionContext.getContext().getParameters();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		pageBean = this.baseAllService.getCustomerService().findRecCustomerList(admin, customer, map);
		this.map.clear();
		this.map.put("total", this.pageBean.getTotalRow());
		this.map.put("data", this.pageBean.getResult());
		formatJSON(response, this.map);
		return null;
	}
	
	/**
	 * @desc 短信信息添加页面
	 * @return
	 * @author hufq
	 * @datetime 2014年10月14日,上午10:36:58
	 */
	@Action(value = "customer_manage_add", results = {@Result(name = SUCCESS, location = "customer_manage_add.jsp")})
	public String manageAdd(){
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String customerId = this.baseAllService.getCustomerService().customerSave(admin, customer);			// 保存客户
		customer.setId(customerId);
		return SUCCESS;
	}
	
	/**
	 * @desc 保存客户信息
	 * @return
	 * @author kangyj
	 * @datetime 2014年11月4日,上午11:50:42
	 */
	@Action(value = "customer_save")
	public String save() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String customerId = this.baseAllService.getCustomerService().saveCustomer(customer, admin);
		map.put("success", true);
		map.put("customerId", customerId);
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 修改客户信息
	 * @return
	 * @author kangyj
	 * @datetime 2014年11月9日,上午10:22:03
	 */
	@Action(value = "customer_edit")
	public String edit() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(customer.getId())) {
			this.baseAllService.getCustomerService().editCustomer(customer);
			map.put("success", true);
		}else {
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 查询客户电话和客户姓名地址
	 * @return
	 * @author kangyj
	 * @datetime 2014年11月21日,下午4:39:57
	 */
	@Action(value = "customer_find_info")
	public String findCustomerAndPhoneNo() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		// 正在输入订单数
		List<MedicalOrders> ordresList = this.baseAllService.getOrdersManagerService().findInputOrders(customer.getId());
		Integer usePoints = 0;
		BigDecimal useMoney = new BigDecimal(0);
		Integer useRed = 0;
		for(MedicalOrders ordres : ordresList) {
			if(StringUtils.isBlank(customer.getOrdersId()) || !ordres.getId().equals(customer.getOrdersId())) {
				usePoints += ordres.getUsePoints();
				useMoney = useMoney.add(ordres.getUseMoney());
				useRed = ordres.getUseRed();
			}
		}
		map.put("usePoints", usePoints);
		map.put("useMoney", useMoney);
		map.put("useRed", useRed);
		
		// 查询客户，设置媒体、订单性质
		customer = this.baseAllService.getCustomerService().findCustomerById(customer, admin);
		
		// 联系电话
		List<String> contactNoList = this.baseAllService.getCallMyManagerService().findMainNo(customer.getId());
		if(contactNoList.size() > 0 && contactNoList.size() == 1) {
			customer.setContactNo(contactNoList.get(0));
		} else if(contactNoList.size() > 0 && contactNoList.size() == 2) {
			customer.setContactNo(contactNoList.get(0));
			customer.setContactNos(contactNoList.get(1));
		}
		
		// 客户已下单数
		Long ordersCount = this.baseAllService.getOrdersManagerService().getOrdersCount(customer.getId(), customer.getOrdersId());
		customer.setOrdersCount(ordersCount);
		
		// 允许退单数
		customer.setHospitalId(admin.getEnterpriseId());
		String backCount = this.baseAllService.getCustomerService().findBackCount(customer);
		customer.setBackCount(backCount);
		
		map.put("customer", customer);
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 订单页面修改客户级别
	 * @return
	 * @author kangyj
	 * @datetime 2014年11月24日,下午5:26:27
	 */
	@Action(value = "customer_edit_level")
	public String editLevel() {
		this.baseAllService.getCustomerService().editCustomerLevel(customer);
		return null;
	}
	
	/**
	 * @desc 推荐客户信息页面初始化
	 * @return
	 * @author kangyj
	 * @datetime 2014年12月5日,下午3:56:43
	 */
	@Action(value = "customer_recommend_init", results = {@Result(location = "customer_recommend_init.jsp")})
	public String recommendInit() {
		return SUCCESS;
	}
	
	/**
	 * @desc 推荐客户查询
	 * @return
	 * @author kangyj
	 * @datetime 2014年12月5日,下午3:59:43
	 */
	@Action(value = "customer_recommend_view")
	public String recommendView() {
		HttpServletResponse response = ServletActionContext.getResponse();
		list = this.baseAllService.getCustomerService().findRecommendCustomer(customer.getId());
		formatJSON(response, list);
		return null;
	}
	
	/**
	 * @desc 跳转到推荐客户添加页面（同时生成一条任务和客户信息）
	 * @return
	 * @author kangyj
	 * @datetime 2014年12月6日,下午2:43:23
	 */
	@Action(value = "customer_recommend_add", results = {@Result(location = "customer_recommend_add.jsp")})
	public String recommendAdd() {
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String callId = this.baseAllService.getCallMyManagerService().saveRecommendCall(admin);// 生成当前话务员的未处理任务
		customer.setCallId(callId);
		String customerId = this.baseAllService.getCustomerService().customerSave(admin, customer);			// 保存客户
		customer.setCallId(callId);
		customer.setCallStatus(SystemConfig.CALL_TASK_UNTREATED);
		customer.setId(customerId);
		return SUCCESS;
	}
	
	/**
	 * @desc 推荐客户信息保存
	 * @return
	 * @author kangyj
	 * @datetime 2014年12月5日,下午6:57:17
	 */
	@Action(value = "customer_recommend_save")
	public String recommendSave() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(customer.getId()) && StringUtils.isNotBlank(customer.getCallId())) {
			this.baseAllService.getCustomerService().editCustomer(customer);
			this.baseAllService.getCallMyManagerService().updateReCallNum(customer.getContactNo(), customer.getCallId());
			map.put("success", true);
		} else {
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 删除推荐信息（客户信息未保存，关闭弹窗进行删除）
	 * @return
	 * @author kangyj
	 * @datetime 2015年1月21日,下午4:03:12
	 */
	@Action(value = "customer_recommend_del")
	public String delRecommend() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(StringUtils.isNotBlank(customer.getCallId()) && StringUtils.isNotBlank(customer.getId())) {
			customer.setHospitalId(admin.getEnterpriseId());
			this.baseAllService.getCallMyManagerService().delRecommend(customer);
			map.put("success", true);
		} else {
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 推荐客户信息修改
	 * @return
	 * @author kangyj
	 * @datetime 2014年12月6日,下午3:39:16
	 */
	@Action(value = "customer_recommend_edit", results = {@Result(location = "customer_recommend_edit.jsp")})
	public String recommendSaveEdit() {
		customer.setCallStatus(SystemConfig.CALL_TASK_UNTREATED);
		return SUCCESS;
	}
	
	/**
	 * @desc 批量加入黑名单
	 * @return null
	 * @author liy
	 * @datetime 2014年12月11日,下午9:25:29
	 */
	@Action(value = "customer_add_black")
	public String addBlack() {
		this.baseAllService.getCallMyManagerService().updateCustomerBlack(this.customer.getIds());
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		map.put("success", true);
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 批量移出黑名单
	 * @return null
	 * @author liy
	 * @datetime 2014年12月11日,下午11:04:46
	 */
	@Action(value = "customer_out_black")
	public String outBlack() {
		this.baseAllService.getCallMyManagerService().updateCustomerBlackOut(this.customer.getIds());
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		map.put("success", true);
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 下载模版
	 * @return null
	 * @author liy
	 * @datetime 2014年12月30日,下午2:21:45
	 */
	@Action(value = "customer_import_download")
	public String customerImportDownload() {
		this.download(SystemConfig.CUSTOMER_IMPORT_FILE, "导入客户模版.xls");
		return null;
	}
	
	/**
	 * @desc 导入客户到任务
	 * @return
	 * @author kangyj
	 * @datetime 2015年2月10日,下午3:09:58
	 */
	@Action(value = "customer_import_to_call")
	public String importToCall() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(StringUtils.isNotBlank(customer.getId()) || StringUtils.isNotBlank(customer.getContactNo())) {
			this.baseAllService.getCustomerService().importToCall(admin, customer);
			map.put("success", true);
		} else {
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 设置允许客户退单数
	 * @return
	 * @author kangyj
	 * @datetime 2015年2月16日,下午2:57:11
	 */
	@Action(value = "customer_set_back_count")
	public String setBackCount() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		customer.setHospitalId(admin.getEnterpriseId());
		this.baseAllService.getCustomerService().setBackCount(customer);
		map.put("success", true);
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 跳转到查看客户详细信息页面
	 * @return
	 * @author kangyj
	 * @datetime 2015年2月28日,下午2:29:21
	 */
	@Action(value = "customer_detail_view", results = {@Result(location = "customer_detail_view.jsp")})
	public String customerDetailView() {
		return SUCCESS;
	}
	
	/**
	 * @desc 保存新赠客户信息
	 * @return String
	 * @author kangyj
	 * @datetime 2015年4月10日,下午3:31:36
	 */
	@Action(value = "customer_save_new")
	public String saveNew() {
		HttpServletResponse response = ServletActionContext.getResponse();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		customer.setHospitalId(admin.getEnterpriseId());
		this.baseAllService.getCustomerService().editCustomer(customer);
		map = new HashMap<String, Object>();
		map.put("success", true);
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 未保存用户信息，删除用户及电话号码
	 * @return String
	 * @author kangyj
	 * @datetime 2015年4月16日,下午10:03:09
	 */
	@Action(value = "customer_del_new")
	public String delNew() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(customer.getId())) {
			this.baseAllService.getCustomerService().delNewCustomer(customer);
			map.put("success", true);
		} else {
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	
	
	@Override
	public MedicalCallCustomer getModel() {
		return customer;
	}
}
